<template>
  <div class="app-container">
      <div>
        <el-form>
          <el-row class="rowFormItem">
            <el-col :span="3">
              <el-input v-model="keyword" placeholder="请输入导师昵称搜索" />
            </el-col>
            <!-- 提交按钮 -->
            <el-col :span="5" class="clear">
              <el-form-item style="text-align: center;width: 250px;margin-left: 10px;">
                <el-button type="primary" size="large" @click="handleSubmit()">检索</el-button>
                <el-button type="success" size="large" @click="addmodel()">添加</el-button>
                <el-button type="warning" size="large" style="margin-left: 8px" @click="handleReset()">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <el-table :data="formdata" v-loading="loading" border style="width: 100%" :header-cell-style="{background:'#eef1f6',color:'#606266'}">
        <el-table-column align="center" prop="id" label="序号" />
        <el-table-column align="center" prop="photo_url" label="头像">
          <template slot-scope="scope">
            <el-button type="text" size="medium">
              <img style="width: 50%;" :src="scope.row.photo_url" />
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="name" label="姓名" />
        <el-table-column align="center" prop="sex" label="性别">
        <template slot-scope="scope">
            <div v-if="scope.row.sex=='male'">男</div>
            <div v-if="scope.row.sex=='female'">女</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="phone" label="手机" />
        <el-table-column align="center" prop="email" label="邮箱" />
        <el-table-column align="center" prop="area" label="地区">
          <template slot-scope="scope">
            <div>{{scope.row.area}}</div>
          </template>
        </el-table-column>
       <!-- <el-table-column align="center" prop="desc" label="简介" /> -->
       <el-table-column align="center" prop="detail" label="简介">
          <template slot-scope="scope">
              <el-popover
                  placement="bottom"
                  title="简介"
                  width="300"
                  trigger="hover"
                  :content="scope.row.desc">
                  <div slot="reference" class="ellipsisThree">{{scope.row.desc}}</div>
                </el-popover>
            </template>
         </el-table-column>
        <el-table-column align="center" prop="created_at" label="注册时间" />
        <el-table-column label="操作" align="center" width="230px">
          <template slot-scope="scope">
            <el-button class="btnAppeal" size="small" type="warning" @click="updateMsg(scope.row)">修改</el-button>
            <el-button class="btnAppeal" size="small" type="danger" @click="delMsg(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    <!-- 添加模态款 -->
    <el-dialog style="margin: auto;" :close-on-click-modal="false" :title="title" :visible.sync="modelMsg">
      <div class="msgDiv">
        <!-- <h3>店铺基础信息</h3> -->
        <div>
          <el-form ref="form" :model="form" label-width="80px">
            <el-form-item v-show="vshow" label="序号">
              <el-input v-model="form.id" disabled></el-input>
            </el-form-item>
            <el-form-item label="姓名" :required="true">
              <el-input v-model="form.name" placeholder="请输入导师的姓名"></el-input>
            </el-form-item>
            <el-form-item label="手机">
              <el-input v-model="form.phone" placeholder="请输入导师的手机号码"></el-input>
            </el-form-item>
            <el-form-item label="邮箱">
              <el-input v-model="form.email" placeholder="请输入导师的邮箱"></el-input>
            </el-form-item>
            <el-form-item label="性别" :required="true"  style="text-align: left;">
               <el-radio v-model="form.sex" label="male">男</el-radio>
               <el-radio v-model="form.sex" label="female">女</el-radio>
            </el-form-item>
            <el-form-item label="地址" prop="origin" style="text-align: left;">
              <el-cascader placeholder="选择所在的地址" :options="ORIGIN" :props="{value:'label'}" v-model="form.area"
                filterable></el-cascader>
            </el-form-item>
            <el-form-item label="简介">
              <el-input v-model="form.desc" placeholder="请输入个人简介"></el-input>
            </el-form-item>
            <el-form-item label="详细" style="text-align: left;">
             <!-- <el-input v-model="form.sort" placeholder="请输入个人详细介绍"></el-input> -->
            <!--  <el-input v-model="form.detail" type="textarea" placeholder="此处输入个人的详细介绍"></el-input> -->
              <div id="editorDiv"  style="text-align: left;width: 100%;margin: auto;">
              </div>
            </el-form-item>
            <!-- 封面图片 -->
            <el-form-item label="头像"  :required="true" style="text-align: left;">
              <el-tooltip placement="top">
                <div slot="content">请上传个人头像</div>
                <i class="el-icon-info" style="font-size: 18px;"></i>
              </el-tooltip>
              <el-upload class="avatar-uploader" action="https://qiashangyun.rzkeji.com/api/file/upload-img/" name='photo'
                :show-file-list="false" :on-success="handleAvatarSuccess">
                <img v-if="form.photo_url" :src="form.photo_url" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!-- 封面图片end -->
          </el-form>
          <el-button type="success" @click="addMsg(form)">{{addORupdate}}</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 分页 -->
    <div style="text-align: center;">
      <el-pagination background layout="prev, pager, next" @current-change="pageChange" :current-page="startpage" :page-size="pageSize"
        :total="totalusers" />
    </div>
     </div>
</template>

<script>
 import ORIGIN from '../../assets/json/origin.json'
 import E from 'wangeditor'
  export default {
    data() {
      return {
       ORIGIN,
        modelMsg: false,
        keyword:"",
        form: {
          id: "",
          name: "",
          phone: "",
          email: "",
          sex: "",
          area: "",
          desc:"",
          detail:"",
          photo_id: "",
          photo_url: ""
        },
        vshow: false,
        loading: false,
        title: "",
        addORupdate: "", //添加或修改
        formdata: [],
        totalusers: 0, //总行数
        pageSize: 5, //每页几行
        startpage: 1 ,//起始页
        /* 富文本 */
        editorContent: '',
        editor: null
      }

    },
    watch:{
      modelMsg(newVal){
        console.log("打开=="+newVal)
        if(newVal==true){
           this.reloadRichText()
        }
      }
    },
    mounted() {
       this.getTeacherList()
    },
    methods: {
      reloadRichText(){
          console.log(this.editor)
         this.$nextTick(() => {
         const editor = new E('#editorDiv')
        // 默认情况下，显示所有菜单
        editor.config.menus = [
            'head',
            'bold',
            'fontSize',
            'fontName',
            'italic',
            'underline',
            'strikeThrough',
            'indent',
            'lineHeight',
            'foreColor',
            'backColor',
            'link',
            'list',
            'todo',
            'justify',
            'quote',
            'emoticon',
            // 'image',
            // 'video',
            'table',
            'code',
            'splitLine',
            'undo',
            'redo',
        ]
        editor.create();
        this.editor = editor
        this.editor.txt.html(this.form.detail) //如果有值，把值赋入富文本
        })
      },
      checkPhone(phoneNumb) {
        var user = /^1[0-9]{10}$/
        if (!user.test(phoneNumb)) {
          this.$message({
            message: '请输入正确的手机号码',
            type: 'error'
          });
          return false
        }
        return true
      },
      checkEmail(email) {
        var user = /^\w+@[a-zA-Z0-9]{2,10}(?:\.[a-z]{2,4}){1,3}$/
        if (!user.test(email)) {
          this.$message({
            message: '请输入正确邮箱格式',
            type: 'error'
          });
          return false
        }
        return true
      },
      //获取分页列表
      getTeacherList() {
        let params = {
          "page": this.startpage,
          "limit": this.pageSize,
          "keyword":this.keyword
        }
        //调用后台提供的接口方法
        this.$api.getTeacherList(params).then(res => {
          if(res.data.level=="success"){
            this.formdata = res.data.data
            this.totalusers = res.data.page_info.total
            this.loading = false
          }else{
            this.$message.error(res.data.message)
          }

        })
      },
      handleSubmit(){
        this.getTeacherList()
      },
      handleReset(){
        this.keyword=""
      },
      //分页 pageChange当前页发生改变触发函数
      async pageChange(page) {
        this.startpage = page
        this.loading = true
        //调用获取列表的方法
        this.getTeacherList()
      },
      addmodel() {
        this.modelMsg = true
        this.title = '添加导师信息'
        this.addORupdate = "添加",
        this.vshow = false
        this.form.id="",
        this.form.name= "",
        this.form.phone= "",
        this.form.email= "",
        this.form.sex="male",
        this.form.area= "",
        this.form.desc="",
        this.form.detail="",
        this.form.photo_id= "",
        this.form.photo_url= ""
      },
      //提交店铺入驻申请
      async addMsg(form) {
         let checkPhone=""
         let checkEmail=""
        if(form.phone !=""){
          checkPhone = this.checkPhone(form.phone)
          if(!checkPhone){
            return false
          }
        }
        if(form.email !=""){
           checkEmail = this.checkEmail(form.email)
           if(!checkEmail){
             return false
           }
        }
        this.form.detail = this.editor.txt.html() //获取富文本的值赋值提交

        //判断带星号的是否为空
       if ((form.name && form.sex && form.photo_id) == "") {
          this.$message({
            message: "带星号为必填项，请完善信息！",
            type: "warning"
          })
          return false;
        }

          /* 显示加载中。。。 */
          const loadingOne = this.$loading({
            lock: true,
            text: '保存中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })

          if (form.id > 0) {
            /* 修改 */
            console.log(form)
            await this.$api.setTeacher(form).then(res => {
              console.log(res)
              this.$message({
                type: res.data.level,
                message: res.data.message
              });
              if (res.data.level == "success") {
                this.getTeacherList()
                loadingOne.close()
                this.modelMsg = false
              } else {
                this.modelMsg = true
                loadingOne.close()
              }

            })
          } else {
            /* 添加 */
             console.log(form)
            await this.$api.setTeacher(form).then(res => {
              this.$message({
                type: res.data.level,
                message: res.data.message
              });
              if (res.data.level == "success") {
                this.getTeacherList()
                loadingOne.close()
                this.modelMsg = false
              } else {
                this.modelMsg = true
                loadingOne.close()
              }

            })
          }
          this.modelMsg = false
      },
      //修改弹出框
      updateMsg(data) {
        console.log("data")
        console.log(this.editor)
        this.modelMsg = true
        this.title = '修改导师信息'
        this.addORupdate = "修改",
        this.vshow = true
          this.form.id = data.id,
          this.form.name= data.name,
          this.form.phone= data.phone,
          this.form.email= data.email,
          this.form.sex = data.sex,
          this.form.desc=data.desc,
          this.form.detail=data.detail,
          this.form.photo_id= data.photo_id,
          this.form.photo_url= data.photo_url
          this.form.area = data.area.split("/")
      },
   //删除店铺信息
      async delMsg(id) {
        let delid = {
          id: id
        }
        await this.$confirm('此操作将永久删除该信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {

          this.$api.delTeacher(delid).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            if (res.data.level == "success") {
              this.getTeacherList()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      //图片上传
      handleAvatarSuccess(res, file) {
        //console.log(res.data.id)
        this.form.photo_id = res.data.id
        //console.log(file)
        this.form.photo_url = res.data.img_url;
      },
    }
  }
</script>
<style scoped="scoped">
  /deep/.el-card__header {
    background-color: #409EFF;
    color: whitesmoke;
  }

  /deep/.el-dialog {
   margin-top: 2vh !important;
  }

  .msgDiv {
    width: 80%;
    margin: auto;
    text-align: center;
  }

  .el-input {
    display: flex;
    flex-grow: <2>;
  }
  /deep/.el-textarea__inner{
    min-height: 100px !important;
  }

  /* 图片上传css */
  .avatar-uploader /deep/.el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }

  .avatar {
    width: 100px;
    height: 100px;
    display: block;
  }
</style>
